package cn.juque.jdfsystem.disruptor.event;

import cn.hutool.core.collection.CollUtil;
import cn.juque.common.base.DisruptorBody;
import cn.juque.common.constants.StringConstants;
import cn.juque.common.disruptor.IBusinessEventService;
import cn.juque.jdfsystem.disruptor.bo.FileChangeBodyBO;
import cn.juque.jdfsystem.task.FileChangeTask;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>FileChangeDisruptorEventServiceImpl</li>
 * </ul>
 * @date 2023-01-11 18:59:30
 **/
@Service("fileChangeDisruptorEventService")
public class FileChangeDisruptorEventServiceImpl implements IBusinessEventService {

    public static final String BEAN = "fileChangeDisruptorEventService";

    @Resource
    private FileChangeTask fileChangeTask;

    /**
     * 具体消费者的实现
     *
     * @param disruptorBody 消息体
     */
    @Override
    public void invoke(DisruptorBody disruptorBody) {
        if (!(disruptorBody instanceof FileChangeBodyBO)) {
            return;
        }
        FileChangeBodyBO fileChangeBodyBO = (FileChangeBodyBO) disruptorBody;
        List<String> validFileIdList = fileChangeBodyBO.getValidFileIdList();
        List<String> invalidFileIdList = fileChangeBodyBO.getInValidFileIdList();
        int arrayLength = 0;
        int validSize = CollUtil.size(validFileIdList);
        if(validSize > 0) {
            arrayLength = arrayLength + validFileIdList.size();
        }
        if(CollUtil.isNotEmpty(invalidFileIdList)) {
            arrayLength = arrayLength + invalidFileIdList.size() + 1;
        }
        // 存放参数
        String[] args = new String[arrayLength];
        if(validSize > 0) {
            for (int i = 0; i < validFileIdList.size(); i++) {
                args[i] = validFileIdList.get(i);
            }
        }
        if(CollUtil.isNotEmpty(invalidFileIdList)) {
            args[validSize] = StringConstants.COMMA;
            // 偏移值
            int offset = validSize + 1;
            for (int i = 0; i < invalidFileIdList.size(); i++) {
                args[i + offset] = invalidFileIdList.get(i);
            }
        }
        this.fileChangeTask.start(args);
    }
}
